//
//  HDCFFixThrowViewController.m
//  HaoDeCaiFu
//
//  Created by admin on 2017/12/23.
//  Copyright © 2017年 郑开宏. All rights reserved.
//

#import "HDCFFixThrowViewController.h"
#import "FixThrowSetView.h"
#import "FixThrowTableViewCell.h"
#import "FixThrowView.h"//选择弹框
#import "HDCFOpenAccountVc.h"//是否开户页面
#import "HDCFRiskTestVc.h"
#import "InputPassWordView.h"
#import "HDCFMyBankCardVc.h"//我的银行卡页面
#import "FixThrowRule.h"//定投规则弹窗

@interface HDCFFixThrowViewController ()<UITableViewDelegate,UITableViewDataSource,FixThrowSetViewDelegate,FixThrowTableViewCellDelegate,InputPassWordViewDelegate,HDCFMyBankCardVcDelegate>
{
    //定投周期
    NSString * cycle;
    //定投日期
    NSInteger cycleDay;
    //扣款失败是否顺延 默认为1，顺延扣款；如果选择为0，不顺延扣款
    NSInteger postponeDeduction;
    //投资组合 (定投类型)
    NSString * type;
    
    NSArray * periodArr;//定投周期数组
    NSArray * dateArr;//定投日期数组
    NSArray * typeArr;//投资组合数组
    
    NSInteger periodIndex;//定投周期的索引
    NSInteger dateIndex;//定投日期的索引
    NSInteger typeIndex;//投资组合的索引
    
    NSString * fixThrowName;//定投计划名称
    NSString * buyAmount;//购买金额
    
    NSNumber *salesChargesRate;//费率
    NSNumber *salesCharges;//费用
    
    NSArray * bankCardDataArray;//银行卡数组
    NSArray * bankNameArray;//银行名称数组
    
    NSInteger bankCardIndex;
    
    BOOL isEditOne;//是否修改过银行卡
    //在已经编辑过情况下使用的参数
    NSString * bankName;
    NSString * bankCode;
    NSString * bankIds;
    BOOL isBank;
}
@property(nonatomic,strong)UITableView * tableView;
@property (nonatomic, weak) UIView *hitView;
@property (nonatomic, copy) NSString *tradePassword;
@end

static NSString * identifierOne = @"cell";
static NSString * identifierThree = @"cellThree";
static NSString * identifierTwo = @"FixThrowTableViewCell";
@implementation HDCFFixThrowViewController
-(void)setDataDic:(NSDictionary *)dataDic
{
    _dataDic = dataDic;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"定投";
    self.view.backgroundColor = RGB(233, 233, 233);
    
    
    periodArr  = [NSArray array];
    periodArr = @[@"每月",@"每两周",@"每周",@"每季"];
    dateArr  = [NSArray array];
    dateArr = @[@"1日",@"2日",@"3日",@"4日",@"5日",@"6日",@"7日",@"8日",@"9日",@"10日",@"11日",@"12日",@"13日",@"14日",@"15日",@"16日",@"17日",@"18日",@"19日",@"20日",@"21日",@"22日",@"23日",@"24日",@"25日",@"26日",@"27日",@"28日"];
    typeArr  = [NSArray array];
    typeArr = @[@"个别投资项目"];
    periodIndex = 0;
    dateIndex = 0;
    typeIndex = 0;
    postponeDeduction = 1;//扣款顺延
    salesChargesRate = 0;//费率
    salesCharges = 0;//费用
    buyAmount = @"";
    bankCardDataArray = [NSArray array];
    bankNameArray = [NSArray array];
    bankCardIndex = 0;
    isEditOne = NO;
    
    [self initTableView];
    [self initBottomView];
    
    //得到银行信息
    [self getBankName];
    //得到银行卡信息
    [self getBankCardInfo];
}
-(void)initTableView
{
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = RGB(233, 233, 233);
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:identifierOne];
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:identifierThree];
    [self.tableView registerNib:[UINib nibWithNibName:@"FixThrowTableViewCell" bundle:nil] forCellReuseIdentifier:identifierTwo];
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
//    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(mainRefresh)];
//    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(mainLoadMore)];
}
-(UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc]init];
        _tableView.frame = CGRectMake(0, 0, screenWidth, screenHeight - 49-KNavHeight);
        //_tableView.backgroundColor = [UIColor yellowColor];
        [self.view addSubview:_tableView];
    }
    return _tableView;
}
-(void)initBottomView
{
    //提交按钮
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(0 ,screenHeight - 49-KNavHeight , screenWidth, 49);
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [btn setTitle:@"提交" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(fixThrowCommit) forControlEvents:UIControlEventTouchUpInside];
    //[btn setBackgroundColor:ZKcolor(184, 27, 36)];
    [btn setBackgroundColor:COLOR_NAV];
    [self.view addSubview:btn];
}
#pragma mark -
#pragma mark 事件
//提交
-(void)fixThrowCommit
{
    //LLLog(@"%@",_dataDic);
    //先判断是否登录
    NSString *token = kToken;
    if (!(token.length > 0)) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"请先登录！" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            HDCFLoginVc *loginVc = [[HDCFLoginVc alloc] init];
            [self.navigationController pushViewController:loginVc animated:NO];
            
        }];
        UIAlertAction * action2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        
        [alert addAction: action1];
        [alert addAction: action2];
        [self presentViewController:alert animated:NO completion:nil];
        return;
    }
    
    //在判断是否开户
    NSString *openStatus = kOpenStatus;
    if (!(openStatus.integerValue > 0)){
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"请先开户！" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            HDCFOpenAccountVc *loginVc = [[HDCFOpenAccountVc alloc] init];
            [self.navigationController pushViewController:loginVc animated:NO];

        }];
        UIAlertAction * action2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

        }];

        [alert addAction: action1];
        [alert addAction: action2];
        [self presentViewController:alert animated:NO completion:nil];
        return;
    }
    
    if (fixThrowName.length < 1) {
        [SVProgressHUD showInfoWithStatus:@"请输入定投计划名称"];
        [SVProgressHUD dismissWithDelay:1.0];
        return;
    }
    
    if (buyAmount.length < 1) {
        [SVProgressHUD showInfoWithStatus:@"请输入购买金额"];
        [SVProgressHUD dismissWithDelay:1.0];
        return;
    }
    
    
    NSString *fundStatus = _dataDic[@"fundStatus"];
    double minMoney = 0.0;
    double maxMoney = 0.0;
    if ([fundStatus isEqualToString:@"0"]) {
        NSNumber *minInitialIpoAmount = _dataDic[@"minInitialIpoAmount"];
        minMoney = minInitialIpoAmount.doubleValue;
        NSNumber *maxIpoAmount = _dataDic[@"maxIpoAmount"];
        maxMoney = maxIpoAmount.doubleValue;
       // self.limitMoney.text = [NSString stringWithFormat:@"(%.2f---%.2f)", minInitialIpoAmount.doubleValue, maxIpoAmount.doubleValue];
    }
    else if ([fundStatus isEqualToString:@"1"]){
        NSNumber *maxBuyAmount = _dataDic[@"maxBuyAmount"];
        NSNumber *minInitialBuyAmount = _dataDic[@"minInitialBuyAmount"];
        //self.limitMoney.text = [NSString stringWithFormat:@"(%.2f---%.2f)", minInitialBuyAmount.doubleValue, maxBuyAmount.doubleValue];
        minMoney = minInitialBuyAmount.doubleValue;
        maxMoney = maxBuyAmount.doubleValue;
    }
    
    //CGFloat buyMoney = money.doubleValue;
    if ([buyAmount doubleValue] < minMoney) {
        [SVProgressHUD showInfoWithStatus:@"低于最小购买金额"];
        [SVProgressHUD dismissWithDelay:1.0];
        return;
    }
    if ([buyAmount doubleValue] > maxMoney) {
        [SVProgressHUD showInfoWithStatus:@"大于最大购买金额"];
        [SVProgressHUD dismissWithDelay:1.0];
        return;
    }

    NSNumber *selfRiskRate = kRiskResult;
    if (!selfRiskRate) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"请先进行风险评测！" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            HDCFRiskTestVc *riskVc = [[HDCFRiskTestVc alloc] init];
            [self.navigationController pushViewController:riskVc animated:NO];

        }];
        UIAlertAction * action2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

        }];

        [alert addAction: action1];
        [alert addAction: action2];
        [self presentViewController:alert animated:NO completion:nil];
        return;
    }

    NSNumber *funfRiskRate = _dataDic[@"riskRate"];
    //如果自己是保守型，那么除了保守型基金其他都不能购买
    if ([selfRiskRate isEqual:@1]) {
        if (funfRiskRate.integerValue > selfRiskRate.integerValue) {
            [SVProgressHUD showInfoWithStatus:@"您的风险等级为保守型，不能购买超过风险等级的产品"];
            [SVProgressHUD dismissWithDelay:1.5];
            return;
        }

    }

    if (funfRiskRate.integerValue > selfRiskRate.integerValue) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"友情提示" message:@"此基金的购买风险超出您的风险承受能力，确定要购买吗？" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            UIWindow *window = [UIApplication sharedApplication].keyWindow;
            UIView *view = [[UIView alloc] init];
            self.hitView = view;
            UITapGestureRecognizer *r5 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(viewHit)];
            r5.numberOfTapsRequired = 1;
            [view addGestureRecognizer:r5];

            view.frame = CGRectMake(0, 0, screenWidth, screenHeight);
            view.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0.1];
            InputPassWordView *inputView = [InputPassWordView InputPassWordView];
            inputView.frame = CGRectMake(30, (screenHeight - 182) / 2, screenWidth - 60, 182);
            inputView.layer.cornerRadius = 5.0;
            inputView.layer.shadowColor = ZKcolor(100, 100, 100).CGColor;//shadowColor阴影颜色
            inputView.layer.shadowOffset = CGSizeMake(0,0);//shadowOffset阴影偏移,x向右偏移4，y向下偏移4，默认(0, -3),这个跟shadowRadius配合使用
            inputView.layer.shadowOpacity = 0.7;//阴影透明度，默认0
            inputView.layer.shadowRadius = 3;//阴影半径，默认3
            inputView.clipsToBounds = YES;
            inputView.delegate = self;

            [view addSubview:inputView];
            [window addSubview:view];
        }];
        UIAlertAction * action2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

        }];

        [alert addAction: action1];
        [alert addAction: action2];
        [self presentViewController:alert animated:NO completion:nil];
    }else{
        UIWindow *window = [UIApplication sharedApplication].keyWindow;
        UIView *view = [[UIView alloc] init];
        self.hitView = view;
        UITapGestureRecognizer *r5 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(viewHit)];
        r5.numberOfTapsRequired = 1;
        [view addGestureRecognizer:r5];

        view.frame = CGRectMake(0, 0, screenWidth, screenHeight);
        view.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0.1];
        InputPassWordView *inputView = [InputPassWordView InputPassWordView];
        inputView.frame = CGRectMake(30, (screenHeight - 182) / 2, screenWidth - 60, 182);
        inputView.layer.cornerRadius = 5.0;
        inputView.layer.shadowColor = ZKcolor(100, 100, 100).CGColor;//shadowColor阴影颜色
        inputView.layer.shadowOffset = CGSizeMake(0,0);//shadowOffset阴影偏移,x向右偏移4，y向下偏移4，默认(0, -3),这个跟shadowRadius配合使用
        inputView.layer.shadowOpacity = 0.7;//阴影透明度，默认0
        inputView.layer.shadowRadius = 3;//阴影半径，默认3
        inputView.clipsToBounds = YES;
        inputView.delegate = self;

        [view addSubview:inputView];
        [window addSubview:view];
    }
}
//下拉刷新
//-(void)mainRefresh
//{
//
//}
//上拉加载
//-(void)mainLoadMore
//{
//      
//}
//定投规则
-(void)fixThrowRule
{
    NSString * title = @"定投规则";
    NSString * contentOne = @"1.客户创建的定投计划，将于D+1个自然日生效。例如，您1月1日创建的定投计划，那定投计划内容将于1月2日生效。";
    NSString * contentTwo = @"2.扣款日为发起定投交易的日期，如果扣款日当天为非工作日，那么定投订单的交易日期为下一个工作日。";
    NSString * contentThree = @"3.扣款失败顺延是指定投计划在扣款日扣款失败，继续于下一个自然日发起扣款的操作来保障定投计划的连续性功能。";
    NSMutableArray * content = [NSMutableArray array];
    [content addObject:contentOne];
    [content addObject:contentTwo];
    [content addObject:contentThree];
    [FixThrowRule shareWithContent:content title:title];
}
- (void)viewHit{
    [self.hitView removeFromSuperview];
}
#pragma mark -
#pragma mark requestData
//得到银行卡数据
- (void)getBankCardInfo{
    NSMutableDictionary *paramets = [NSMutableDictionary dictionary];
    
    paramets[@"accountNumber"] = kAcount;
    NSString *jsonStr = [self dictionaryToJson:paramets];
    NSDictionary *paramet = @{KparametOne:jsonStr,
                              KparametTwo:KBankCardInfo};
    
    [HttpRequest sendGetRequestWithURL:nil WithParamets:paramet success:^(id result) {
        NSString *code = result[@"code"];
        if ([code isEqualToString:@"0000"]) {
            NSDictionary *dict = result[@"data"];
            NSDictionary *dictTwo = dict[@"investorBankDetails"];
            bankCardDataArray = dictTwo[@"data"];
            //LLLog(@"%@",bankCardDataArray);
            //一个section刷新
            NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:0];
            [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
        }else{
            [SVProgressHUD showInfoWithStatus:result[@"message"]];
            [SVProgressHUD dismissWithDelay:1.0];
        }
        
    } failure:^(NSError *errer) {
        [SVProgressHUD showErrorWithStatus:@"获取银行卡信息失败"];
        [SVProgressHUD dismissWithDelay:1.0];
    }];
}
- (void)getBankName{
    NSDictionary *paramet = @{
                              KparametTwo:@"/public/investor/find-bank"
                              };
    [HttpRequest sendGetRequestWithURL:nil WithParamets:paramet success:^(id result) {
        LLLog(@"%@",result);
        NSDictionary *dict = result[@"data"];
        bankNameArray = [NSArray arrayWithArray:dict[@"data"]];
        
    } failure:^(NSError *errer) {
        [SVProgressHUD showErrorWithStatus:@"网络错误"];
        [SVProgressHUD dismissWithDelay:1.0];
    }];
}
//得到费率以及费用的请求
- (void)getRateFee{
    NSMutableDictionary *paramets = [NSMutableDictionary dictionary];
    
    paramets[@"fundCode"] = _dataDic[@"fundCode"];
    paramets[@"investmentAmount"] = buyAmount;
    NSString *jsonStr = [self dictionaryToJson:paramets];
    NSDictionary *paramet = @{KparametOne:jsonStr,
                              KparametTwo:KGetFee};
    
    [HttpRequest sendGetRequestWithURL:nil WithParamets:paramet success:^(id result) {
        NSString *code = result[@"code"];
        if ([code isEqualToString:@"0000"]) {
            NSDictionary *dict = result[@"data"];
            if (![dict[@"salesChargesRate"] isKindOfClass:[NSNull class]]) {
                salesChargesRate = dict[@"salesChargesRate"];
                //self.consultRate.text = [NSString stringWithFormat:@"%.2f%%", salesChargesRate.doubleValue];
            }
            if (![dict[@"salesCharges"] isKindOfClass:[NSNull class]]) {
                salesCharges = dict[@"salesCharges"];
                //self.consultCost.text = [NSString stringWithFormat:@"%.2f元", salesCharges.doubleValue];
            }
            
            //刷新对应的section
            NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:2];
            [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
        }else{
            [SVProgressHUD showInfoWithStatus:result[@"message"]];
            [SVProgressHUD dismissWithDelay:1.0];
            
            buyAmount = @"";
            salesChargesRate = 0;
            salesCharges = 0;
            //刷新对应的section
            NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:2];
            [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
        }
        
    } failure:^(NSError *errer) {
        [SVProgressHUD showErrorWithStatus:@"服务器错误"];
        [SVProgressHUD dismissWithDelay:1.0];
        
        buyAmount = @"";
        salesChargesRate = 0;
        salesCharges = 0;
        //刷新对应的section
        NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:2];
        [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
    }];
}
//发起定投的请求
-(void)initDataOfFixThrow
{
    [SVProgressHUD show];
    //定投周期
    NSArray * cycleArray = [NSArray array];
    cycleArray = @[@"monthly",@"biweekly",@"weekly",@"quarterly"];
    
    
    NSArray * dateArray = [NSArray array];
    if (dateArr.count == 28) {
        dateArray = @[@1,@2,@3,@4,@5,@6,@7,@8,@9,@10,@11,@12,@13,@14,@15,@16,@17,@18,@19,@20,@21,@22,@23,@24,@25,@26,@27,@28];
    }else
    {
        dateArray = @[@1,@2,@3,@4,@5];
    }
    
    NSMutableDictionary *productsInfo = [NSMutableDictionary dictionary];
    productsInfo[@"fundCode"] = self.dataDic[@"fundCode"];
    productsInfo[@"currency"] = @"156";
    productsInfo[@"rspAmount"] = buyAmount;//定投金额
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[@"accountNumber"] = kAcount;
    dict[@"cycle"] = cycleArray[periodIndex];
    dict[@"cycleDay"] = dateArray[dateIndex];
    dict[@"investorPayId"] = bankCardDataArray[bankCardIndex][@"investorPayId"];
    dict[@"password"] = self.tradePassword;//交易密码
    dict[@"postponeDeduction"] = [NSString stringWithFormat:@"%ld",postponeDeduction];
    dict[@"products"] = [NSArray arrayWithObjects:productsInfo, nil];
    dict[@"riskConfirmed"] = @"0";//风险确认
    dict[@"rspName"] = fixThrowName;
    dict[@"targetAmount"] = @"";
    dict[@"type"] = @"";
    //LLLog(@"%@",dict);
    NSString *jsonString = [self dictionaryToJson:dict];
    NSDictionary *dictThree = @{
                                KparametTwo:@"/public/transaction/create-rsp-fund-plan"
                                };
    [HttpRequest sendPostRequestWithURL:nil WithParamets:dictThree WithJsonString:jsonString success:^(id result) {
        [SVProgressHUD dismiss];
        //NSLog(@"%@",result);
        
        if ([result[@"code"] isEqualToString:@"0000"]) {
            [SVProgressHUD showSuccessWithStatus:@"定投成功"];
            [SVProgressHUD dismissWithDelay:1.0];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.navigationController popViewControllerAnimated:YES];
            });
        }else{
            [SVProgressHUD showInfoWithStatus:result[@"message"]];
            [SVProgressHUD dismissWithDelay:1.5];
        }
    } failure:^(NSError *errer) {
        [SVProgressHUD showErrorWithStatus:@"服务器错误，购买失败"];
        [SVProgressHUD dismissWithDelay:1.0];
    }];
}
#pragma mark -
#pragma mark UITableViewDelegate,UITableViewDataSource

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:identifierOne];
    if (!cell) {
        cell = [tableView dequeueReusableCellWithIdentifier:identifierOne forIndexPath:indexPath];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    
    UITableViewCell * cellTwo = [tableView dequeueReusableCellWithIdentifier:identifierThree];
    if (!cellTwo) {
        cellTwo = [tableView dequeueReusableCellWithIdentifier:identifierThree forIndexPath:indexPath];
    }
    cellTwo.selectionStyle = UITableViewCellSelectionStyleNone;
    
    if (indexPath.section == 0) {
        if (bankCardDataArray.count > 0)
        {
            UIView * cellView = [[UIView alloc]init];
            cellView.backgroundColor = [UIColor whiteColor];
            cellView.frame = CGRectMake(0, 0, screenWidth, 50+30);
            [cell addSubview:cellView];

            UILabel * firstLabel = [[UILabel alloc]init];
            firstLabel.text = @"支付方式";
            firstLabel.font = [UIFont systemFontOfSize:12];
            firstLabel.frame = CGRectMake(10, 15, [self calculateWidth:firstLabel.text], 20);
            firstLabel.textColor = RGB(0,0,0);
            [cellView addSubview:firstLabel];


            NSDictionary * dict = bankCardDataArray[bankCardIndex];
            NSString *banName;
            NSString *cardNo;
            NSString *laterFour;
            for (int i = 0; i < bankNameArray.count; i++) {
                NSDictionary * bankNameDict = bankNameArray[i];
                if ([bankNameDict[@"bankCode"] isEqualToString:dict[@"bankCode"]])
                {
                    banName = bankNameDict[@"bankName"];
                    cardNo = dict[@"bankNumber"];
                    laterFour = [cardNo substringFromIndex:(cardNo.length - 4)];
                    break;
                }
            }
            
            UILabel * secondLabel = [[UILabel alloc]init];
            if ([banName isKindOfClass:[NSNull class]] || [laterFour isKindOfClass:[NSNull class]]) {
                secondLabel.text = [NSString stringWithFormat:@"---"];
            }
            else
            {
                secondLabel.text = [NSString stringWithFormat:@"%@  ***%@", banName, laterFour];
            }
            secondLabel.font = [UIFont systemFontOfSize:14];
            secondLabel.frame = CGRectMake(10, firstLabel.bottom + 5, [self calculateWidth:secondLabel.text], 20);
            secondLabel.textColor = RGB(0,0,0);
            [cellView addSubview:secondLabel];

            UIImageView * rightImageView = [[UIImageView alloc]init];
            rightImageView.frame = CGRectMake(screenWidth -10 -20, 26, 20, 20);
            rightImageView.image = [UIImage imageNamed:@"icon_right"];
            [cellView addSubview:rightImageView];

            UIView * bottomView = [[UIView alloc]init];
            bottomView.frame = CGRectMake(0, 70, screenWidth, 8);
            bottomView.backgroundColor = RGB(233, 233, 233);
            [cellView addSubview:bottomView];
        }
        else
        {
            UIView * cellView = [[UIView alloc]init];
            cellView.backgroundColor = [UIColor whiteColor];
            cellView.frame = CGRectMake(0, 0, screenWidth, 50+30);
            [cell addSubview:cellView];


            UIView * headerTwoView = [UIView new];
            headerTwoView.frame = CGRectMake(0, 0, screenWidth, 30);
            headerTwoView.backgroundColor = RGB(253,245,230);
            [cellView addSubview:headerTwoView];

            UIImageView * imageView = [[UIImageView alloc]init];
            imageView.frame = CGRectMake(10, 5, 20, 20);
            imageView.image = [UIImage imageNamed:@"icon_tanhao"];
            [headerTwoView addSubview:imageView];


            UILabel * titleLabel = [[UILabel alloc]init];
            titleLabel.text = @"您需要绑定银行卡才能进行交易";
            titleLabel.font = [UIFont systemFontOfSize:14];
            titleLabel.frame = CGRectMake(imageView.right +10, 5, [self calculateWidth:titleLabel.text], 20);
            titleLabel.textColor = RGB(255,165,0);
            [headerTwoView addSubview:titleLabel];



            UIImageView * addImageView = [[UIImageView alloc]init];
            addImageView.frame = CGRectMake(10, 40, 20, 20);
            addImageView.image = [UIImage imageNamed:@"icon_add"];
            [cellView addSubview:addImageView];

            UILabel * titlesLabel = [[UILabel alloc]init];
            titlesLabel.text = @"添加银行卡";
            titlesLabel.font = [UIFont systemFontOfSize:14];
            titlesLabel.frame = CGRectMake(addImageView.right +10, 40, [self calculateWidth:titlesLabel.text], 20);
            titlesLabel.textColor = RGB(255,165,0);
            [cellView addSubview:titlesLabel];

            UIImageView * rightImageView = [[UIImageView alloc]init];
            rightImageView.frame = CGRectMake(screenWidth -10 -20, 40, 20, 20);
            rightImageView.image = [UIImage imageNamed:@"icon_right"];
            [cellView addSubview:rightImageView];

            UIView * bottomView = [[UIView alloc]init];
            bottomView.frame = CGRectMake(0, 70, screenWidth, 8);
            bottomView.backgroundColor = RGB(233, 233, 233);
            [cellView addSubview:bottomView];
        }
        
    }
    else if (indexPath.section ==1)
    {
        FixThrowSetView * blueView = [FixThrowSetView fixTrowSetView];
        blueView.delegate = self;
        //cell.contentView.size = CGSizeMake(screenWidth, 260);
        blueView.frame = CGRectMake(10, 0, screenWidth, 250);
        cellTwo.contentView.frame = CGRectMake(0, 0, screenWidth+20, 250);
        [cellTwo.contentView addSubview:blueView];

        if (fixThrowName.length > 0) {
            blueView.nameTextField.text = fixThrowName;
        }
        blueView.periodLabel.text = periodArr[periodIndex];
        blueView.dateLabel.text = dateArr[dateIndex];
        blueView.groupLabel.text = typeArr[typeIndex];

        UIView * bottomView = [[UIView alloc]init];
        bottomView.frame = CGRectMake(0,260, screenWidth, 8);
        bottomView.backgroundColor = RGB(233, 233, 233);
        [cellTwo addSubview:bottomView];
        
        return cellTwo;
    }
    else if (indexPath.section == 2)
    {
        FixThrowTableViewCell * fixCell = [tableView dequeueReusableCellWithIdentifier:identifierTwo];
        if (!fixCell) {
            fixCell = [tableView dequeueReusableCellWithIdentifier:identifierTwo forIndexPath:indexPath];
        }
        
        if (self.dataDic) {
            fixCell.delegate = self;
            fixCell.nameLabel.text = self.dataDic[@"fundName"];
            fixCell.codeLabel.text = self.dataDic[@"fundCode"];
            NSArray * riskArray = @[@"低风险",@"中低风险",@"中风险",@"中高风险",@"高风险"];
            fixCell.riskLabel.text = riskArray[[self.dataDic[@"riskRate"] integerValue]-1];
            fixCell.rateLabel.text = [NSString stringWithFormat:@"%.2f%%", salesChargesRate.doubleValue];
            fixCell.costLabel.text = [NSString stringWithFormat:@"%.2f元", salesCharges.doubleValue];
            fixCell.amountTextfield.text = buyAmount;
            fixCell.dataDic = self.dataDic;
        }
        
        fixCell.selectionStyle = UITableViewCellSelectionStyleNone;
        return fixCell;
    }
    
    return cell;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 2) {
        return 1;
    }
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 80;
    }
    else if (indexPath.section == 1)
    {
        return 268;
    }
    return 150.0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 1) {
        return 40;
    }
    else if (section == 0)
    {
        return 0.0;
    }
    return 0.0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.0;
}
- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
//        UIView * headerTwoView = [UIView new];
//        headerTwoView.frame = CGRectMake(0, 0, screenWidth, 30);
//        headerTwoView.backgroundColor = RGB(253,245,230);
//
//        UIImageView * imageView = [[UIImageView alloc]init];
//        imageView.frame = CGRectMake(10, 5, 20, 20);
//        imageView.image = [UIImage imageNamed:@"icon_tanhao"];
//        [headerTwoView addSubview:imageView];
//
//
//        UILabel * titleLabel = [[UILabel alloc]init];
//        titleLabel.text = @"您需要绑定银行卡才能进行交易";
//        titleLabel.font = [UIFont systemFontOfSize:14];
//        titleLabel.frame = CGRectMake(imageView.right +10, 5, [self calculateWidth:titleLabel.text], 20);
//        titleLabel.textColor = RGB(255,165,0);
//        [headerTwoView addSubview:titleLabel];
//        return headerTwoView;
    }
    else if (section == 1) {
        UIView * headerTwoView = [UIView new];
        headerTwoView.frame = CGRectMake(0, 0, screenWidth, 40);
        headerTwoView.backgroundColor = [UIColor whiteColor];
        
        UILabel * titleLabel = [[UILabel alloc]init];
        titleLabel.text = @"定投计划设置";
        titleLabel.font = [UIFont systemFontOfSize:16];
        titleLabel.frame = CGRectMake(10, 10, [self calculateWidth:titleLabel.text], 20);
        titleLabel.textColor = RGB(0, 0, 0);
        [headerTwoView addSubview:titleLabel];
        
        UIButton * ruleBut = [[UIButton alloc]init];
        NSMutableAttributedString *title = [[NSMutableAttributedString alloc] initWithString:@"定投规则"];
        NSRange titleRange = {0,[title length]};
        [title addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:titleRange];
        [ruleBut setAttributedTitle:title
                                  forState:UIControlStateNormal];
        [ruleBut.titleLabel setFont:[UIFont systemFontOfSize:14]];
        ruleBut.titleLabel.textColor = RGB(153, 153, 153);
        [ruleBut addTarget:self action:@selector(fixThrowRule) forControlEvents:UIControlEventTouchUpInside];
        ruleBut.frame = CGRectMake(screenWidth - 10 - [self calculateWidth:ruleBut.titleLabel.text], 10, [self calculateWidth:ruleBut.titleLabel.text], 20);
        [headerTwoView addSubview:ruleBut];
        
        return headerTwoView;
    }
    return nil;
}
- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return nil;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section ==0) {
        //点击添加银行卡
        HDCFMyBankCardVc * bankCardVC = [[HDCFMyBankCardVc alloc]init];
        bankCardVC.delegate = self;
        bankCardVC.isHiddenDeleteBtn = YES;
        //bankCardVC.isXianshiWallet = YES;
        //bankCardVC.isNeedBlock = YES;
//        [bankCardVC setBlock:^(NSString *name, NSString *bank, NSString *bankId, BOOL isBankCard) {
//            LLLog(@"%@ %@ %@ %d",name,bank,bankId,isBankCard);
//            bankName = name;
//            bankCode = bank;
//            bankIds = bankId;
//            isBank = isBankCard;
//
//            isEditOne = YES;
//            //一个section刷新
//            NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:0];
//            [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
//        }];
        [self.navigationController pushViewController:bankCardVC animated:YES];
    }
}
#pragma mark -
#pragma mark FixThrowTableViewCellDelegate
-(void)fixThrowTableViewCellReturnAmountValue:(NSString *)amount
{
    buyAmount = amount;
    [self getRateFee];
}
#pragma mark -
#pragma mark FixThrowSetViewDelegate
-(void)fixThrowSetViewReturnIndex:(NSInteger)index
{
    if (index == 0) {
        //LLLog(@"每日");
        [FixThrowView shareWithContent:periodArr title:@"定投周期" index:periodIndex];
        [FixThrowView returnClickIndexBlock:^(long indexs) {
            //LLLog(@"点击了%ld",indexs);
            periodIndex = indexs;
            if (periodIndex == 0) {
                dateArr = @[@"1日",@"2日",@"3日",@"4日",@"5日",@"6日",@"7日",@"8日",@"9日",@"10日",@"11日",@"12日",@"13日",@"14日",@"15日",@"16日",@"17日",@"18日",@"19日",@"20日",@"21日",@"22日",@"23日",@"24日",@"25日",@"26日",@"27日",@"28日"];
            }
            else if (periodIndex == 1)
            {
                dateArr = @[@"星期一",@"星期二",@"星期三",@"星期四",@"星期五"];
            }
            else if (periodIndex == 2)
            {
                dateArr = @[@"星期一",@"星期二",@"星期三",@"星期四",@"星期五"];
            }
            else if (periodIndex == 3)
            {
                dateArr = @[@"1日",@"2日",@"3日",@"4日",@"5日",@"6日",@"7日",@"8日",@"9日",@"10日",@"11日",@"12日",@"13日",@"14日",@"15日",@"16日",@"17日",@"18日",@"19日",@"20日",@"21日",@"22日",@"23日",@"24日",@"25日",@"26日",@"27日",@"28日"];
            }
            //一个section刷新
            NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:1];
            [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
        }];
    }
    else if (index ==1)
    {
        //LLLog(@"定投日期");
       
        [FixThrowView shareWithContent:dateArr title:@"定投日期" index:dateIndex];
        [FixThrowView returnClickIndexBlock:^(long indexs) {
            LLLog(@"点击了%ld",indexs);
            dateIndex = indexs;
            //一个section刷新
            NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:1];
            [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
        }];
    }
    else if (index ==2)
    {
        //LLLog(@"个人投资");
        [FixThrowView shareWithContent:typeArr title:@"投资组合" index:typeIndex];
        [FixThrowView returnClickIndexBlock:^(long indexs) {
            LLLog(@"点击了%ld",indexs);
            typeIndex = indexs;
            //一个section刷新
            NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:1];
            [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
        }];
    }
    else if (index ==3)
    {
        //点击是（扣款失败顺延）
        postponeDeduction = 1;//顺延扣款
    }
    else if (index ==4)
    {
        //点击否（扣款失败顺延）
        postponeDeduction = 0;//不顺延扣款
    }
    //选择后刷新对应的section
    
}
-(void)fixThrowSetViewReturnNameTextfield:(NSString *)name
{
    fixThrowName = name;
}
#pragma mark -
#pragma mark HDCFMyBankCardVcDelegate
-(void)HDCFMyBankCardVcReturnSelectIndex:(NSInteger)index bankCardArray:(NSArray * )bankCarkArr
{
    bankCardIndex = index;
    bankCardDataArray = bankCarkArr;
    //一个section刷新
    NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:0];
    [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
}
#pragma mark -
#pragma mark InputPassWordViewDelegate
- (void)cancelClick{
    [self.hitView removeFromSuperview];
}
- (void)confirmClickWithPassWord:(NSString *)password{
    self.tradePassword = password;
    [self.hitView removeFromSuperview];
    if (password.length < 1) {
        [SVProgressHUD showInfoWithStatus:@"请输入交易密码"];
        [SVProgressHUD dismissWithDelay:1.0];
        return;
    }
    
    [self initDataOfFixThrow];
}
#pragma mark -
#pragma mark 计算字符串长度
- (CGFloat)calculateWidth:(NSString *)str {
    NSDictionary *dic  = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:17], NSFontAttributeName, nil];
    CGSize size = [str sizeWithAttributes:dic];
    return size.width;
}
#pragma mark -
#pragma mark 字典转json字符串
- (NSString *)dictionaryToJson:(NSDictionary *)dic{
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSString *jsonTemp = [jsonString stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    return jsonTemp;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
